package cm.tl.pms.util.compute;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import lombok.extern.slf4j.Slf4j;
import parsii.eval.Parser;
import parsii.tokenizer.ParseException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: lwp
 * @date: 2023/2/25-02-25 17:00
 * @description
 * @version: 1.0
 */
@Slf4j
public class ParsiiUtil {
    static DecimalFormat df = new DecimalFormat("#.##");

    /**
     * 替换公式中的特殊符号为可识别符号
     *
     * @param exp
     * @return
     */
    public static String transitionFormula(String exp) {

//        exp = "＋";
        //全角转半角
        exp = CharUtil.toDbc(exp);
        //所有字符转为小写
        exp = exp.toLowerCase();


        exp = exp
                .replaceAll("﹢", "+")
                .replaceAll("十", "+")
                .replaceAll("┼", "+")
                .replaceAll("╋", "+")
                .replaceAll("╬", "+")
                .replaceAll("﹣", "-")
                .replaceAll("一", "-")
//                .replaceAll("x", "*")
                .replaceAll("×", "*")
                .replaceAll("╳", "*")
//                .replaceAll("х", "*")
                .replaceAll("·", "*")
                .replaceAll("÷", "/")
                .replaceAll("\\{", "(")
                .replaceAll("}", ")")
                .replaceAll("\\[", "(")
                .replaceAll("]", ")")
        ;

        //包含百分号
        if (exp.contains("%")) {
            //获取包含百分号的数字
            List<String> resultFindAll = ReUtil.findAll("([\\\\d])*%|(\\\\d{1,10}).([\\\\d])*%", exp, 0, new ArrayList<String>());


            if (CollUtil.isNotEmpty(resultFindAll)) {
                for (String s : resultFindAll) {
                    s = s.trim();
                    String replace = s.replace("%", "");
                    BigDecimal bigDecimal = new BigDecimal(replace);
                    bigDecimal = bigDecimal.divide(new BigDecimal(100));
                    exp = exp.replaceAll(s, bigDecimal.toString());

                }
            }

            System.out.println(resultFindAll);
        }

        return exp;
    }

    /**
     * 计算分数
     *
     * @param formula
     * @return
     * @throws ParseException
     */
    public static double calculateScore(String formula) throws ParseException {
        double evaluate = 0.00;
        evaluate = Parser.parse(formula).evaluate();
        return evaluate;
    }

    /**
     * 计算分数并保留指定小数位数
     *
     * @param formula       公式
     * @param decimalPlaces 保留小数位数
     * @return 计算结果
     * @throws ParseException
     */
    public static double calculateScore(String formula, int decimalPlaces) throws Exception {
        double evaluate = calculateScore(formula);
        // 使用 BigDecimal 保留指定小数位数
        BigDecimal result = new BigDecimal(evaluate).setScale(decimalPlaces, RoundingMode.HALF_UP);
        return result.doubleValue();
    }

    public static String compute(String expressionStr) {
        String rs = "0";
        try {
            String suffix = "";
            if (expressionStr.endsWith("%")) {
                expressionStr = expressionStr.substring(0, expressionStr.length() - 1);
                suffix = "%";
            }
            // 将方括号替换为圆括号
            expressionStr = expressionStr.replace("[", "(").replace("]", ")");
            // 创建 Expression 对象
            double result = calculateScore(expressionStr, 2);
            rs = df.format(result);
            return rs + suffix;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return rs;
        }
    }

    public static String getDoubleByFieldId(String val) {
        try {
            val = val.replaceAll(" ", "");
            val = val.replaceAll(",", "");
            val = val.replaceAll("，", "");
            val = val.replaceAll("元", "");
            Double dv = Double.valueOf(val);
            return val;
        } catch (Exception e) {
            log.error("无法解析成Long的值:{}", val);
        }
        return "0";
    }

    public static void main(String[] args) {
        String str = "";
        // 净利润-同比变动 |(a-b)/b|
        str = "|(-1159491820.84--345734007.56)/-345734007.56|";
        System.out.println("净利润-同比变动 : " + compute(str));
        // 经营性现金流-同比变动
        str = "|(87398062.07-79089243.15)/79089243.15|";
        System.out.println("经营性现金流-同比变动 : " + compute(str));
        // 存货周转率
        str = "9092365528.8/[(821994448.72+594807573.35)/2]*100%";
        System.out.println("存货周转率 : " + compute(str));
        // 销售收入-上年年末数
        str = "6350051694.79+0";
        System.out.println("销售收入-上年年末数 : " + compute(str));
        // 经营净现金流-上年年末数
        str = "-19859369.46+0";
        System.out.println("经营净现金流-上年年末数 : " + compute(str));
    }

}
